package com.clouddot.baipai.ui.util.asy;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;

@SuppressLint("HandlerLeak")
public class AsyHelper
{
	private final int Error = -1;
	private final int Success = 0;

	private Thread thread;
	private AsyCallbackListener callback;
	private AsyExecuteListener exelistener;

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);

			if (msg.what == Success)
			{
				Object result = msg.obj;
				callback.run(result);
			} else
			{
				callback.error((Exception) msg.obj);
			}
		}
	};

	public void execute(AsyExecuteListener listener, AsyCallbackListener callback)
	{
		this.exelistener = listener;
		this.callback = callback;
		Runnable run = new Runnable()
		{
			@Override
			public void run()
			{
				try
				{
					Object result = exelistener.run();
					Message msg = new Message();
					msg.what = Success;
					msg.obj = result;
					handler.sendMessage(msg);
				} catch (Exception ex)
				{
					Message msg = new Message();
					msg.what = Error;
					msg.obj = ex;
					handler.sendMessage(msg);
				}
			}
		};
		thread = new Thread(run);
		thread.start();
	}

	public static void create(AsyExecuteListener listener, AsyCallbackListener callback)
	{
		AsyHelper asyHelper = new AsyHelper();
		asyHelper.execute(listener, callback);
	}
}
